<?php
namespace tp5_lib\user\extension;

use think\Model;
use tp5_lib\user\model\MobileCodeModel;
use tp5_lib\user\controller\BaseLoginController;

/**
 * 所有第三方登录控制器的基类
 * @property Model $outside 第三方用户信息表
 */
abstract class OutsideController extends BaseLoginController
{
    /**
     * 将第三方返回的数据转换成用户表中的格式
     * @param string[] $data
     * @return string[]
     */
    protected function convertUserInfo($data)
    {
        $user=[
            "username"=>"",
            "mobile"=>"",
            "email"=>"",
            "nickname"=>"",
            "avatar"=>"",
            "signature"=>"",
            "sex"=>"",
            "birthday"=>"",
            "url"=>"",
        ];
        return $user;
    }
    /**
     * 第三方登录绑定账号页面
     */
    public function bindAccount()
    {
        if(!$id=input("id")){
            $this->error("第三方用户编号不能为空");
        }
        $record=$this->outside->db()->where(["id"=>$id])->find()->toArray();
        $user=$this->convertUserInfo($record);
        $redirect_url=url("doBindAccount",["id"=>$id]);
        $url=url("user/login/login")."?redirect_url=".$redirect_url;

        $this->assign("id",$id);
        $this->assign("user",$user);
        $this->assign("bind_account_url",$url);
        return $this->fetch("user@public/pc/bindAccount");
    }
    /**
     * 使用第三方用户信息创建新用户
     */
    public function doOutsideRegister()
    {
        if(!$id=input("id")){
            $this->error("第三方用户编号不能为空");
        }
        $mobile=input("mobile");
        $code=new MobileCodeModel();
        if(!$code->check($mobile,input("code"),"register")){
            $this->error($code->getError());
        }
        $record=$this->outside->db()->where(["id"=>$id])->find()->toArray();
        $user=$this->convertUserInfo($record);
        $user["mobile"]=$mobile;
        $user=$this->logic->doRegister($user);
        $this->outside->db()->where(["id"=>$id])->setField("user_id",$user["id"]);
        $this->loginRedirect($user,"创建成功");
    }
    /**
     * 绑定原有账号
     */
    public function doBindAccount()
    {
        if(!$id=input("id")){
            $this->error("第三方用户编号不能为空");
        }
        $user=$this->checkLogin();
        $this->outside->db()->where(["id"=>$id])->setField("user_id",$user["id"]);
        $this->loginRedirect($user,"绑定成功");
    }
}
